import os,time
from PIL import Image
import sqlite3 as db

class Proc:
  def __init__(self):
    self.basepath = "/AIplatform/web/"
    self.imgpath = self.basepath + "static/images/"
    self.newimgpath = self.basepath + "static/dist/"
    self.dbpath = self.basepath + "abc.db"
    self.conn = db.connect(self.dbpath)
    self.cursor = self.conn.cursor()
    self.conn.row_factory = db.Row

  def proc(self):
    self.cursor.execute("select * from imgs where done=0")
    rows = self.cursor.fetchall()
    for row in rows:
      img = self.imgpath + row[1]
      if row[2] != "":
        newpath = self.newimgpath + row[2] + "/"
        if not os.path.exists(newpath):
          os.makedirs(newpath)
        newimg = newpath + str(row[0]) + "_" + row[1]
        self.mkfile(img,newimg,row[5],row[6],row[7],row[8])
        self.update(row[0])
        print row[1]
 
  def update(self,id):
    self.cursor.execute("update imgs set done=1 where id=%s"%(id))
    self.conn.commit()

  def mkfile(self,src,dst,top,left,width,height):
    f = Image.open(src)
    box=(left,top,width+left,height+top)
    f.crop(box).save(dst)
 
if __name__ == "__main__":
  proc = Proc()
  while True:
    proc.proc()
    time.sleep(10)
    print "..."

